import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { AuthService } from '@auth/index';
import { FriendEntity } from '@modules/friend/entity/friend.entity';
import { DynamicEntity } from './entity/dynamic.entity';
import { CreateDynamicDto } from './dto/index';

@Injectable()
export class DynamicService {
  constructor(
    private readonly authService: AuthService,
    @InjectRepository(DynamicEntity)
    private readonly dynamicEntity: Repository<DynamicEntity>,
    @InjectRepository(FriendEntity)
    private readonly friendEntity: Repository<FriendEntity>,
  ) {}

  /**
   * 发动态
   */
  async createDynamic(token: string, dynamicBody: CreateDynamicDto) {
    const { content, imgUrl = '', status } = dynamicBody;
    const tokenResult = await this.authService.getTokenUser(token);
    const params = { content, imgUrl, status, userId: tokenResult.userId };
    const result = await this.dynamicEntity.save(params);
    return { code: 200, msg: '发布动态成功', data: result };
  }

  /**
   * 获取全部动态
   */
  async getAllDynamic(token: string) {
    const { userId } = await this.authService.getTokenUser(token);
    const findArrData: Array<number> = [userId];
    const friendResult = await this.friendEntity.find({
      where: [{ userId }, { friendId: userId }],
    });
    friendResult.forEach((item) => {
      findArrData.push(item.userId);
      findArrData.push(item.friendId);
    });
    const result = await this.dynamicEntity.find({
      where: { userId: In(findArrData) },
      relations: ['users'],
      order: { id: 'DESC' },
    });
    const formatData = result.map((item) => {
      if (Number(item.userId) === Number(userId)) {
        // type 1: 自己发布的 2: 好友发布的
        return { ...item, type: 1, users: { username: item.users.username, imgUrl: item.users.imgUrl } };
      }
      return { ...item, type: 2, users: { username: item.users.username, imgUrl: item.users.imgUrl } };
    });
    return { code: 200, msg: '获取动态成功', data: formatData };
  }

  /**
   * 获取自己或别人动态
   */
  async getDynamic(token: string, userId: number) {
    const tokenResult = await this.authService.getTokenUser(token);
    const result = await this.dynamicEntity.find({ where: { userId: userId || tokenResult.userId } });
    return { code: 200, msg: '获取动态成功', data: result };
  }

  /**
   * 删除动态
   */
  async deleteDynamic(token: string, id: number) {
    await this.dynamicEntity.createQueryBuilder().delete().where({ id }).execute();
    return { code: 200, msg: '删除动态成功' };
  }

  /**
   * 动态评论
   */
  async dynamicComment() {}

  /**
   * 获取动态评论
   */
  async getDynamicComment() {}
}
